<!--
 * @Description: 基本信息
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-12-27 10:27:09
 * @LastEditTime: 2022-10-31 16:39:06
 * @FilePath: \cscec-pms-admin\src\views\construction\constructionScheduleAdjust\components\BasicInfo.vue
-->
<template>
  <custom-form
    ref="form"
    :is-validate="true"
    :edit-model="''"
    :rules="rules"
    :form="form"
    :form-list="formOption"
    @change="handleChange"
  >
    <template slot="projectId">
      <BaseInput
        v-if="adjustId !== ''"
        disabled
        v-model="viewName"
      />
      <org-tree-select
        v-else
        v-model="form.projectId"
        is-special-tree
        is-need-auth
        is-auto-select-first
        check-strictly
        :extra-query="{
          ifPlanAdjust: 1
        }"
        @select="selectOrg"
      />

      <!--      <a-select-->
      <!--        v-model="form.projectId"-->
      <!--        :disabled="adjustId !== ''"-->
      <!--        placeholder="请选择项目名称"-->
      <!--        @change="handleProjectChange"-->
      <!--      >-->
      <!--        <a-select-option-->
      <!--          v-for="{projectName,projectId,changeStartTime,selectList} in projectList"-->
      <!--          :key="projectId"-->
      <!--          :value="projectId"-->
      <!--          :data="{selectList,changeStartTime}"-->
      <!--        >-->
      <!--          {{ projectName }}-->
      <!--        </a-select-option>-->
      <!--      </a-select>-->
    </template>
    <template
      slot="durationDelayFileList"
      slot-scope="{data:{formItem:{disabled}}}"
    >
      <UploadList
        business-code="PM37"
        :upload-arrys.sync="fileList"
        multiple
        :disabled="disabled"
        :need-chinese-name="true"
        @fileArrysData="handleFileUploaded"
      />
    </template>
  </custom-form>
</template>
<script>
import UploadList from '@/components/UploadList'
import { formOption } from '../model.js'
import { view } from '@/api/construction/constructionScheduleAdjust'
export default {
  name: 'BasicInfo',
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
    // 加载
    loading: {
      type: Boolean,
      require: true
    }
  },
  components: {
    UploadList
  },
  data() {
    return {
      viewName: '',
      // 表单
      form: {
        branchComId: void 0,
        projectId: void 0,
        adjustPlan: void 0,
        reasonId: void 0,
        maxAdjustLevel: void 0,
        changeCompletionTime: void 0,
        changePeriod: void 0,
        durationDelayFileList: void 0,
        comments: void 0
      },
      // 项目列表
      projectList: [],
      // 当前项目开工日期
      changeStartTime: {},
      // 调整计划
      adjustPlan: [],
      // 调整原因
      reasonList: [],
      // 是否隐藏显示上传文件
      showUpload: false,
      // 文件列表
      fileList: []
    }
  },
  computed: {
    // 是查看
    isDetail() {
      return this.$route.query.pageType === 'detail' || this.isAudit
    },
    // 表单项
    formOption() {
      this.$checkRequireItem()
      if (this.adjustId !== '') {
        formOption[0].disabled = true
      } else {
        formOption[0].disabled = false
      }
      formOption[1].data = this.adjustPlan
      formOption[2].data = this.reasonList
      const arr = ['changeCompletionTime', 'changePeriod', 'durationDelayFileList']
      let list = formOption.filter((el) => {
        if (this.form.adjustPlan === 'COMPLETION_PLAN') {
          if (!arr.includes(el.keyName)) {
            return el
          }
        } else {
          if (el.keyName === 'durationDelayFileList') {
            if (!!this.form.changeCompletionTime) {
              return el
            }
          } else {
            return el
          }
        }
      })
      if (this.isDetail) {
        list = list.map((el) => {
          const item = this.$clone(el)
          item.disabled = true
          return item
        })
      }
      return list
    },
    // 表单校验
    rules() {
      const obj = {}
      formOption.map((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    },
    // 调整id
    adjustId() {
      return this.$route.query.id ?? ''
    }
  },
  async mounted() {
    //已经有id需要获取基本信息
    if (this.adjustId !== '') {
      this.$emit('update:loading', true)
      // await this.getProject()
      this.getBasisInfo()
    }
    this.getReason()
  },
  methods: {
    selectOrg(val) {
      if(val.length > 1) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
        this.handleProjectChange2(val[val.length - 1])
      }
    },
    /**
     * @description: 项目名称改变
     * @param {string} value 选中值
     * @param {object} option 节点虚拟dom
     * @return {void}
     */
    handleProjectChange2(data) {
      this.changeStartTime = data.changeStartTime
      this.adjustPlan = data.selectList.map((el) => {
        return {
          value: el.key,
          label: el.value
        }
      })
      this.form.adjustPlan = this.adjustPlan[0].value
      this.$refs.form.clearValidate(['adjustPlan'])
      this.form.changeCompletionTime = void 0
      this.form.changePeriod = void 0
      this.fileList = []
    },
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @param {boolean} toMoment 是否转换为Moment
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 文件列表
     * @param {array} list
     * @return {void}
     */
    handleFileUploaded(list) {
      this.fileList = [...list]
    },
    /**
     * @description: 获取项目列表
     * @param {void}
     * @return {void}
     */
    getProject() {
      return new Promise((resolve, reject) => {
        view
          .queryBasicSelectProject({
            branchComId: this.form.branchComId
          })
          .then(({ code, data }) => {
            if (code === 200) {
              this.projectList = data
            } else {
              this.projectList = []
            }
          })
          .finally(() => {
            resolve()
          })
      })
    },
    /**
     * @description: 获取调整原因
     * @param {void}
     * @return {void}
     */
    getReason() {
      view.planLabel({ type: '12' }).then(({ code, data }) => {
        if (code === 200) {
          this.reasonList = data.map((el) => {
            return {
              value: el.id,
              label: el.name
            }
          })
        } else {
          this.reasonList = []
        }
      })
    },
    /**
     * @description: 获取基本信息
     * @param {void}
     * @return {void}
     */
    getBasisInfo() {
      view
        .basisDetail(this.adjustId)
        .then(({ code, data }) => {
          if (code === 200) {
            this.projectList.push({
              projectName: data.projectName,
              projectId: data.projectId
            })
            this.adjustPlan = [
              {
                value: data.adjustPlan,
                label: data.adjustPlanName
              }
            ]
            this.form.adjustPlan = this.adjustPlan[0].value
            for (let item in this.form) {
              this.form[item] = data[item] || void 0
            }
            this.viewName = data.branchComName + '/' + data.projectName
            this.fileList = data.durationDelayFileList
            this.changeStartTime = (data.changeStartTime ?? '') === '' ? {} : this.moment(data.changeStartTime)
          }
        })
        .finally(() => {
          this.$emit('update:loading', false)
        })
    },
    /**
     * @description: 表单组件改变
     * @param {string} keyName 组件字段名
     * @param {string} value 值
     * @return {void}
     */
    handleChange(keyName, value) {
      // 变更后竣工日期
      if (keyName === 'changeCompletionTime') {
        if (value?._isAMomentObject && JSON.stringify(this.changeStartTime ?? {}) !== '{}') {
          this.form.changePeriod = value.diff(this.changeStartTime, 'day')
        } else {
          this.form.changePeriod = void 0
        }
      }
    },
    /**
     * @description: 项目名称改变
     * @param {string} value 选中值
     * @param {object} option 节点虚拟dom
     * @return {void}
     */
    handleProjectChange(value, option) {
      this.changeStartTime = option.data.attrs.data.changeStartTime
      this.adjustPlan = option.data.attrs.data.selectList.map((el) => {
        return {
          value: el.key,
          label: el.value
        }
      })
      this.form.adjustPlan = this.adjustPlan[0].value
      this.$refs.form.clearValidate(['adjustPlan'])
      this.form.changeCompletionTime = void 0
      this.form.changePeriod = void 0
      this.fileList = []
    },
    /**
     * @description: 提交
     * @param {void}
     * @return {void}
     */
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$emit('update:loading', true)
            const { projectId, adjustPlan, reasonId, changeCompletionTime, changePeriod, comments } = this.form
            // 校验工期顺延资料
            if (changeCompletionTime && this.formatDate(changeCompletionTime, false)) {
              if (this.fileList.length <= 0) {
                this.$message.warning('请上传工期顺延资料')
                this.$emit('update:loading', false)
                reject()
                return
              }
            }
            if (!this.adjustId) {
              // 新增
              view
                .createBasis({
                  projectId,
                  adjustPlan,
                  reasonId,
                  changeCompletionTime: this.formatDate(changeCompletionTime, false) || null,
                  changePeriod,
                  durationDelayFileList: this.fileList.map((el) => el.commonId),
                  comments,
                  changeStartTime: this.formatDate(this.changeStartTime, false)
                })
                .then(({ code, data }) => {
                  if (code === 200) {
                    this.$message.success('新增基本信息成功')
                    this.$router.replace({
                      query: {
                        pageType: this.$route.query.pageType,
                        id: data
                      }
                    })
                    resolve()
                  } else {
                    reject()
                  }
                })
                .catch((error) => {
                  reject()
                })
                .finally(() => {
                  this.$emit('update:loading', false)
                })
            } else {
              // 查看
              if (this.isDetail) {
                this.$emit('update:loading', false)
                resolve()
                return
              }
              // 编辑
              const { projectId, adjustPlan, reasonId, changeCompletionTime, changePeriod, comments } = this.form
              view
                .editDetail({
                  id: this.adjustId,
                  projectId,
                  adjustPlan,
                  reasonId,
                  changeCompletionTime: this.formatDate(changeCompletionTime, false) || null,
                  changePeriod,
                  durationDelayFileList: this.fileList.map((el) => el.commonId),
                  comments,
                  changeStartTime: this.formatDate(this.changeStartTime, false)
                })
                .then(({ code, data }) => {
                  if (code === 200) {
                    if (!this.isDetail) {
                      this.$message.success('编辑基本信息成功')
                    }
                    resolve()
                  } else {
                    reject()
                  }
                })
                .catch((error) => {
                  reject()
                })
                .finally(() => {
                  this.$emit('update:loading', false)
                })
            }
          } else {
            reject()
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
